<?php
/**
 * Created by PhpStorm.
 * User: 郑合达
 * Date: 2018/12/13
 * Time: 17:50
 */

namespace app\mobile\controller;


use app\Model\UsersModel;
use think\Controller;
use app\Model\CartModel;
class UsersLogic extends Controller
{
    public $cateTrre = array();

    /*
        * 登陆
        */
    public function login($username, $password)
    {
        $result = array();

        if (!$username || !$password)
            $result = array('status' => 0, 'msg' => '请填写账号或密码');
        $where=['mobile'=>$username,
                'is_del'=>0
        ];
        $user = UsersModel::where($where)->find();
        if (!$user) {
            $result = array('status' => -1, 'msg' => '账号不存在!');
        } elseif (encryption($password) != $user['password']) {
            $result = array('status' => -2, 'msg' => '密码错误!');
        } elseif ($user['is_lock'] == 1) {
            $result = array('status' => -3, 'msg' => '账号异常已被锁定！！！');
        }else {
            $publics=new Publics();

            $publics->upLevel($user->user_id);//用户信息缓存
            $result = array('status' => 1, 'msg' => '登陆成功');
        }

        return $result;
    }

    /**
     * 用户登录后 需要对购物车 一些操作
     * @param type $session_id
     * @param type $user_id
     */
    public function login_cart_handle($session_id, $user_id)
    {
        if (empty($session_id) || empty($user_id))
            return false;
        // 登录后将购物车的商品的 user_id 改为当前登录的id
        CartModel::where("session_id = '$session_id'")->save(array('user_id' => $user_id));


        // 查找购物车两件完全相同的商品
        $cart_id_arr = CartModel::field('id')->where('user_id', '=', $user_id)->group('goods_id,spec_key')->having('count(goods_id) > 1');

        if (!empty($cart_id_arr)) {
            $cart_id_arr = $this->get_arr_column($cart_id_arr, 'id');
            $cart_id_str = implode(',', $cart_id_arr);
            CartModel::delete($cart_id_str); // 删除购物车完全相同的商品
        }
    }

    function get_arr_column($arr, $key_name)
    {
        $arr2 = array();
        foreach ($arr as $key => $val) {
            $arr2[] = $val[$key_name];
        }
        return $arr2;
    }


    /**
     * 保存公告变量到 smarty中 比如 导航
     */
    public function public_assign()
    {

        $tpshop_config = array();
        $tp_config = Db('tp_config')->cache(true, 31104000)->select();
        foreach ($tp_config as $k => $v) {
            if ($v['name'] == 'hot_keywords') {
                $tpshop_config['hot_keywords'] = explode('|', $v['value']);
            }
            $tpshop_config[$v['inc_type'] . '_' . $v['name']] = $v['value'];
        }

        $goods_category_tree = $this->get_goods_category_tree();
        $this->cateTrre = $goods_category_tree;
//        $this->assign('goods_category_tree', $goods_category_tree);
        $brand_list = Db('brand')->cache(true, 31104000)->field('id,parent_cat_id,logo,is_hot')->where("parent_cat_id>0")->select();
//        $this->assign('brand_list', $brand_list);
//        $this->assign('tpshop_config', $tpshop_config);
        $arr['goods_category_tree']=$goods_category_tree;
        $arr['brand_list']=$brand_list;
        $arr['tpshop_config']=$tpshop_config;
        return $arr;
    }

    /**
     * 获取商品一二三级分类
     * @return type
     */
    function get_goods_category_tree()
    {
        $result = array();
        $cat_list = Db('tp_goods_category')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类

        foreach ($cat_list as $val) {
            if ($val['level'] == 2) {
                $arr[$val['parent_id']][] = $val;
            }
            if ($val['level'] == 3) {
                $crr[$val['parent_id']][] = $val;
            }
            if ($val['level'] == 1) {
                $tree[] = $val;
            }
        }

        foreach ($arr as $k => $v) {
            foreach ($v as $kk => $vv) {
                $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
            }
        }

        foreach ($tree as $val) {
            $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
            $result[$val['id']] = $val;
        }
        return $result;


    }


    /**
     * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
     * @param type $order
     */
    function set_btn_order_status($order)
    {
        $order_status_arr = [
            "WAITPAY" => "待支付",
            "WAITSEND"=> "待发货",
            "WAITRECEIVE" =>  "待收货",
            "WAITCCOMMENT" => "待评价",
            "CANCEL" =>  "已取消",
            "FINISH" =>  "已完成",
            "CANCELLED" => "已作废"
        ];
//        $order=json_decode($order,true);
        $order['order_status_code'] = $order_status_code = $this->orderStatusDesc(0, $order); // 订单状态显示给用户看的
        $order['order_status_desc'] = $order_status_arr[$order_status_code];
        $orderBtnArr = $this->orderBtn(0, $order);

        return array_merge($order,$orderBtnArr); // 订单该显示的按钮
    }
    /**
     * 获取订单状态的 中文描述名称
     * @param type $order_id  订单id
     * @param type $order     订单数组
     * @return string
     */
    function orderStatusDesc($order_id = 0, $order = array())
    {
        if(empty($order))
            $order = Db('tp_order')->where("order_id = $order_id")->find();

        // 货到付款
        if($order['pay_code'] == 'cod')
        {
            if(in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0)
                return 'WAITSEND'; //'待发货',
        }
        else // 非货到付款
        {
            if($order['pay_status'] == 0 && $order['order_status'] == 0)
                return 'WAITPAY'; //'待支付',
            if($order['pay_status'] == 1 &&  in_array($order['order_status'],array(0,1)) && $order['shipping_status'] != 1)
                return 'WAITSEND'; //'待发货',
        }
        if(($order['shipping_status'] == 1) && ($order['order_status'] == 1))
            return 'WAITRECEIVE'; //'待收货',
        if($order['order_status'] == 2)
            return 'WAITCCOMMENT'; //'待评价',
        if($order['order_status'] == 3)
            return 'CANCEL'; //'已取消',
        if($order['order_status'] == 4)
            return 'FINISH'; //'已完成',
        if($order['order_status'] == 5)
            return 'CANCELLED'; //'已作废',
        return 'OTHER';
    }

    function orderBtn($order_id = 0, $order = array())
    {
        if(empty($order))
            $order = Db('tp_order')->where("order_id = $order_id")->find();
        /**
         *  订单用户端显示按钮
        去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
        取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
        确认收货  AND shipping_status=1 AND order_status=0
        评价      AND order_status=1
        查看物流  if(!empty(物流单号))
         */
        $btn_arr = array(
            'pay_btn' => 0, // 去支付按钮
            'cancel_btn' => 0, // 取消按钮
            'receive_btn' => 0, // 确认收货
            'comment_btn' => 0, // 评价按钮
            'shipping_btn' => 0, // 查看物流
            'return_btn' => 0, // 退货按钮 (联系客服)
        );


        // 货到付款
        if($order['pay_code'] == 'cod')
        {
            if(($order['order_status']==0 || $order['order_status']==1) && $order['shipping_status'] == 0) // 待发货
            {
                $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
            }
            if($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
            {
                $btn_arr['receive_btn'] = 1;  // 确认收货
                $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
            }
        }
        // 非货到付款
        else
        {
            if($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付
            {
                $btn_arr['pay_btn'] = 1; // 去支付按钮
                $btn_arr['cancel_btn'] = 1; // 取消按钮
            }
            if($order['pay_status'] == 1 && in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0) // 待发货
            {
                $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
            }
            if($order['pay_status'] == 1 && $order['order_status'] == 1  && $order['shipping_status'] == 1) //待收货
            {
                $btn_arr['receive_btn'] = 1;  // 确认收货
                $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
            }
        }
        if($order['order_status'] == 2)
        {
            $btn_arr['comment_btn'] = 1;  // 评价按钮
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
        if($order['shipping_status'] != 0)
        {
            $btn_arr['shipping_btn'] = 1; // 查看物流
        }
        if($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
        {
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }

        return $btn_arr;
    }


    /*
     * 获取地区列表
     */
    function get_region_list(){
        //获取地址列表 缓存读取

            $region_list = Db('tp_region')->select();
            $region_list = convert_arr_key($region_list,'id');


        return $region_list ;
    }


    /**
     * 记录帐户变动
     * @param   int     $user_id        用户id
     * @param   float   $user_money     可用余额变动
     * @param   int     $pay_points     消费积分变动
     * @param   string  $desc    变动说明
     * @param   float   distribut_money 分佣金额
     * @return  bool
     */
    function accountLog($user_id, $user_money = 0,$pay_points = 0, $desc = '',$distribut_money = 0){
        /* 插入帐户变动记录 */
        $account_log = array(
            'user_id'       => $user_id,
            'user_money'    => $user_money,
            'pay_points'    => $pay_points,
            'user_type'    => 0,
            'change_time'   => time(),
            'desc'   => $desc,
        );
        /* 更新用户信息 */
        $data =[
            'user_money'=>$user_money,
            'pay_points'=>$pay_points,
            'distribut_money'=>$distribut_money
        ];
         $res =Db('tp_users')->where('user_id',$user_id)->Inc($data)->update();
//        $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
//            " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
        if( $res){
            Db('tp_account_log')->insert($account_log);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 给订单送券送积分 送东西
     */
    function order_give($order)
    {
        $order_goods = Db('tp_order_goods')->where("order_id=".$order['order_id'])->cache(true)->select();
        //查找购买商品送优惠券活动
        foreach ($order_goods as $val)
        {
            if($val['prom_type'] == 3)
            {
                $prom = Db('tp_prom_goods')->where('type=3 and id='.$val['prom_id'])->find();
                if($prom){
                    $coupon = Db('tp_coupon')->where("id=".$prom['expression'])->find();//查找优惠券模板
                    if($coupon && $coupon['createnum']>0){
                        $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                        if($remain > 0)
                        {
                            $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                            Db('tp_coupon_list')->insert($data);
                            Db('tp_coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                        }
                    }
                }
            }
        }

        //查找订单满额送优惠券活动
        $pay_time = $order['pay_time'];
        $prom = Db('tp_prom_order')->where("type>1 and end_time>$pay_time and start_time<$pay_time and money<=".$order['order_amount'])->order('money desc')->find();
        if($prom){
            if($prom['type']==3){
                $coupon = Db('tp_coupon')->where("id=".$prom['expression'])->find();//查找优惠券模板
                if($coupon){
                    if($coupon['createnum']>0){
                        $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                        if($remain > 0)
                        {
                            $data = array('cid'=>$coupon['id'],'type'=>$coupon['type'],'uid'=>$order['user_id'],'send_time'=>time());
                            Db('tp_coupon_list')->insert($data);
                            Db('tp_coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                        }
                    }
                }
            }else if($prom['type']==2){
               $this->accountLog($order['user_id'], 0 , $prom['expression'] ,"订单活动赠送积分");
            }
        }
        $points = Db('tp_order_goods')->where("order_id = {$order['order_id']}")->sum("give_integral * goods_num");
        $points && $this->accountLog($order['user_id'], 0,$points,"下单赠送积分");
    }
}